//
//  QiNiu.swift
//  wjkhdfscjkz
//
//  Created by kys-11 on 2019/9/9.
//  Copyright © 2019年 xl123. All rights reserved.
//

import Foundation
let kQiniuBucketljz = "datastructure"
let kQiniuAccessKeyljz = "qoHYw6Xd5u3UeFDevLjk0o6Nx_XQ3Kp_Oe3Qj3f3"
let kQiniuSecretKeyljz = "XngyYNbNinYSs6My59e4sC-YdoYSB8Uu5Li_kyK4"
import Foundation
import UIKit
//import Qiniu
import SwiftyJSON
class QiNiuToolsljz {
    
    static var filePath = String()
    static var sharedInstance = QiNiuToolsljz()
    var Index : Int = 0
    
    init() {
        
    }
    
    func token() -> String {
        return self.createQiniuToken(fileName: kQiniuBucketljz)
    }
    
    func hmacsha1WithString(str: String, secretKey: String) -> NSData {
        
        let cKey  = secretKey.cString(using: String.Encoding.ascii)
        let cData = str.cString(using: String.Encoding.ascii)
        
        var result = [CUnsignedChar](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
        CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result)
        let hmacData: NSData = NSData(bytes: result, length: (Int(CC_SHA1_DIGEST_LENGTH)))
        return hmacData
    }
    func createQiniuToken(fileName: String) -> String {
        
        let oneHourLater = NSDate().timeIntervalSince1970 + 3600
        let putPolicy: NSDictionary = ["scope": kQiniuBucketljz, "deadline": NSNumber(value: UInt64(oneHourLater))]
        //        putPolicy.jsonString()
        let encodedPutPolicy = QNUrlSafeBase64.encode(getJSONStringFromDictionary(dictionary: putPolicy))
        let sign = self.hmacsha1WithString(str: encodedPutPolicy!, secretKey: kQiniuSecretKeyljz)
        
        let encodedSign = QNUrlSafeBase64.encode(sign as Data?)
        
        return kQiniuAccessKeyljz + ":" + encodedSign! + ":" + encodedPutPolicy!
    }
    
    func uploadImageData(image:Data , result: @escaping (_ progress: Float? , _ imageKey:String? ) -> ()) {
        
        
        let token = self.token()
        
        let opt = QNUploadOption(mime: nil, progressHandler: {(key, progres) in
            
            result(progres, nil)
        }, params: nil, checkCrc: true, cancellationSignal: nil)
        
        var cutdownData : Data!
        if (image.count < 9999) {
            cutdownData = image
        } else if (image.count < 99999) {
            let nowImage = UIImage.init(data: image)!
            cutdownData = nowImage.jpegData(compressionQuality: 0.6)
        } else {
            let nowImage = UIImage.init(data: image)!
            cutdownData = nowImage.jpegData(compressionQuality: 0.3)
        }
        
        
        
        if let manager = QNUploadManager() {
            manager.put(cutdownData, key: nil, token: token, complete: { (Info, key, resp) in
                if (Info?.isConnectionBroken)! {
                    //                    NOAlertManager.showErrorHUD("网络连接错误")
                    print("网络连接错误")
                    
                    return
                }
                //                print(resp)
                if let imageKey = resp?["key"] as? String {
                    
                    result(nil, imageKey)
                }
                
            }, option: opt)
        }
        
    }
    
    func uploadVideoData(video:Data , result: @escaping (_ progress: Float? , _ imageKey:String? ) -> ()) {
        
        
        let token = self.token()
        
        let opt = QNUploadOption(mime: nil, progressHandler: {(key, progres) in
            
            result(progres, nil)
        }, params: nil, checkCrc: true, cancellationSignal: nil)
        
        
        
        if let manager = QNUploadManager() {
            manager.put(video, key: nil, token: token, complete: { (Info, key, resp) in
                
                if (Info?.isConnectionBroken)! {
                    //                    NOAlertManager.showErrorHUD("网络连接错误")
                    print("网络连接错误")
                    return
                }
                
                if let imageKey = resp?["key"] as? String {
                    
                    result(nil, imageKey)
                }
                
            }, option: opt)
        }
        
    }
    
    func upVideoDatas(videos:[Data] , result: @escaping (_ progress: Float? , _ imageKey:String? ) -> (),allTasksCompletion:@escaping () -> () ) {
        
        if (Index < videos.count) {
            
            uploadVideoData(video: videos[Index], result: { (progres, imageKey) in
                
                if (imageKey != nil) {
                    
                    result(progres, imageKey)
                    
                    self.Index += 1
                    
                    self.upVideoDatas(videos: videos, result: result, allTasksCompletion: allTasksCompletion)
                }
            })
        }else{
            allTasksCompletion()
            Index = 0
        }
        
    }
    
    
    func upImageDatas(images:[Data] , result: @escaping (_ progress: Float? , _ imageKey:String? ) -> (),allTasksCompletion:@escaping () -> () ) {
        
        if (Index < images.count) {
            
            uploadImageData(image: images[Index], result: { (progres, imageKey) in
                
                if (imageKey != nil) {
                    
                    result(progres, imageKey)
                    
                    self.Index += 1
                    
                    self.upImageDatas(images: images, result: result, allTasksCompletion: allTasksCompletion)
                }
            })
        }else{
            allTasksCompletion()
            Index = 0
        }
        
    }
    
    
    
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try! JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData?
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
}

